import type { StatsCard } from "../../invitation-code/components/StatsCards.vue"
import { computed, ref } from "vue"
// 移除导出功能

// 用户信息接口
export interface UserInfo {
  id: string
  phone: string
  nickname: string
  userType: 0 | 1 | 2 // 0: 付费用户, 1: 试用中, 2: 试用已过期
  version: 0 | 1 | 2 | 3 // 0: 全部版本, 1: 标准版, 2: Pro版, 3: Pro Max版
  invitationCode: string
  agentPath: string
  bindPhone: string
  xiaohongshuAccount?: string
  registrationTime: string
  lastActiveTime: string
  todayData: {
    posts: number
    published: number
  }
  totalData: {
    posts: number
    published: number
  }
  accountStatus: "正常" | "异常"
  trialDaysRemaining?: number // 试用期剩余天数，只有试用用户才有此字段
  isActive: boolean
  dailyLimit: number
  isOnline?: boolean
}

// 统计数据接口（兼容 StatsCards 组件）
export interface UserTrackingStats {
  total: number
  used: number
  pending: number
  expired: number
  exchangeRate: number
  todayGenerated?: number
}

export function useUserTracking() {
  // 页面状态
  const loading = ref(false)
  const searchKeyword = ref("")
  const typeFilter = ref<string | number>("all")
  const statusFilter = ref<string>("all")
  const activityFilter = ref<string>("all")
  const versionFilter = ref<string | number>("all")

  // 分页状态
  const currentPage = ref(1)
  const pageSize = ref(10)
  const total = ref(0)

  // 模拟用户数据
  const users = ref<UserInfo[]>([
    {
      id: "1",
      phone: "13800138888",
      nickname: "李老板的火锅店",
      userType: 0, // 付费用户
      version: 1, // 标准版
      invitationCode: "PKT-STD-A1B2C3",
      agentPath: "华东区域服务商 > 上海代理商A",
      bindPhone: "李老板的火锅店",
      xiaohongshuAccount: "李老板必胜火锅",
      registrationTime: "2024-08-01",
      lastActiveTime: "2024-08-06 14:30",
      todayData: { posts: 12, published: 8 },
      totalData: { posts: 245, published: 189 },
      accountStatus: "正常",
      isActive: true,
      dailyLimit: 2,
      isOnline: false
    },
    {
      id: "2",
      phone: "13800139999",
      nickname: "新手咖啡馆",
      userType: 1, // 试用中
      version: 0, // 无版本
      invitationCode: "",
      agentPath: "",
      bindPhone: "新手咖啡馆",
      xiaohongshuAccount: "新手咖啡馆",
      registrationTime: "2024-08-04",
      lastActiveTime: "2024-08-06 16:45",
      todayData: { posts: 3, published: 1 },
      totalData: { posts: 8, published: 5 },
      accountStatus: "正常",
      trialDaysRemaining: 1, // 剩余1天
      isActive: true,
      dailyLimit: 2,
      isOnline: true
    },
    {
      id: "3",
      phone: "13800137777",
      nickname: "过期试用店",
      userType: 2, // 试用已过期
      version: 0, // 无版本
      invitationCode: "",
      agentPath: "",
      bindPhone: "过期试用店",
      xiaohongshuAccount: "过期试用店",
      registrationTime: "2024-07-25",
      lastActiveTime: "2024-07-29 10:20",
      todayData: { posts: 0, published: 0 },
      totalData: { posts: 6, published: 4 },
      accountStatus: "异常",
      trialDaysRemaining: 0, // 已过期
      isActive: false,
      dailyLimit: 2
    },
    {
      id: "4",
      phone: "13800136666",
      nickname: "西湖美食坊",
      userType: 0, // 付费用户
      version: 2, // Pro版
      invitationCode: "PKT-PRO-D4E5F6",
      agentPath: "华东区域服务商 > 杭州代理商B",
      bindPhone: "西湖美食坊官方",
      xiaohongshuAccount: "杭州西湖美食",
      registrationTime: "2024-08-02",
      lastActiveTime: "2024-08-06 18:20",
      todayData: { posts: 18, published: 15 },
      totalData: { posts: 156, published: 134 },
      accountStatus: "正常",
      isActive: true,
      dailyLimit: 2
    },
    {
      id: "5",
      phone: "13800135555",
      nickname: "刚注册餐厅",
      userType: 1, // 试用中
      version: 0, // 无版本
      invitationCode: "",
      agentPath: "",
      bindPhone: "刚注册餐厅",
      xiaohongshuAccount: "刚注册餐厅",
      registrationTime: "2024-08-06",
      lastActiveTime: "2024-08-06 20:15",
      todayData: { posts: 4, published: 2 },
      totalData: { posts: 4, published: 2 },
      accountStatus: "正常",
      trialDaysRemaining: 3, // 剩余3天
      isActive: true,
      dailyLimit: 2, // 降低限制，让它达到上限
      isOnline: true
    }
  ])

  // 筛选选项
  const userTypeOptions = ref([
    { label: "全部类型", value: "all" },
    { label: "付费用户", value: 0 },
    { label: "试用用户", value: 1 },
    { label: "试用过期", value: 2 }
  ])

  const statusOptions = ref([
    { label: "全部状态", value: "all" },
    { label: "正常", value: "正常" },
    { label: "已禁用", value: "异常" }
  ])

  const activityOptions = ref([
    { label: "全部状态", value: "all" },
    { label: "活跃", value: "true" },
    { label: "不活跃", value: "false" }
  ])

  const versionOptions = ref([
    { label: "全部版本", value: "all" },
    { label: "标准版", value: 1 },
    { label: "Pro版", value: 2 },
    { label: "Pro Max", value: 3 }
  ])

  // 筛选后的用户数据
  const filteredUsers = computed(() => {
    let filtered = users.value

    // 关键词搜索
    if (searchKeyword.value) {
      const keyword = searchKeyword.value.toLowerCase()
      filtered = filtered.filter(user =>
        user.nickname.toLowerCase().includes(keyword)
        || user.phone.includes(keyword)
        || user.bindPhone.toLowerCase().includes(keyword)
        || user.invitationCode.toLowerCase().includes(keyword)
      )
    }

    // 用户类型筛选
    if (typeFilter.value !== "all") {
      filtered = filtered.filter(user => user.userType === typeFilter.value)
    }

    // 账户状态筛选
    if (statusFilter.value !== "all") {
      filtered = filtered.filter(user => user.accountStatus === statusFilter.value)
    }

    // 活跃状态筛选
    if (activityFilter.value !== "all") {
      const isActiveValue = activityFilter.value === "true"
      filtered = filtered.filter(user => user.isActive === isActiveValue)
    }

    // 版本筛选
    if (versionFilter.value !== "all") {
      filtered = filtered.filter(user => user.version === versionFilter.value)
    }

    total.value = filtered.length
    return filtered
  })

  // 分页后的用户数据
  const paginatedUsers = computed(() => {
    const start = (currentPage.value - 1) * pageSize.value
    const end = start + pageSize.value
    return filteredUsers.value.slice(start, end)
  })

  // 统计数据（适配 StatsCards 组件格式）
  const stats = computed((): UserTrackingStats => {
    const totalUsers = users.value.length
    const paidUsers = users.value.filter(u => u.userType === 0).length // 付费用户
    const trialUsers = users.value.filter(u => u.userType === 1).length // 试用中
    const expiredUsers = users.value.filter(u => u.userType === 2).length // 试用已过期
    const todayGenerated = users.value.reduce((sum, u) => sum + u.todayData.posts, 0)
    const todayPublished = users.value.reduce((sum, u) => sum + u.todayData.published, 0)

    return {
      total: totalUsers,
      used: paidUsers,
      pending: trialUsers,
      expired: expiredUsers, // 试用已过期
      exchangeRate: todayPublished, // 今日发布内容
      todayGenerated // 今日生成内容
    }
  })

  // 统计卡片数据
  const statsCards = computed<StatsCard[]>(() => [
    {
      label: "总用户数",
      value: stats.value.total,
      description: "占比 40%",
      icon: "User",
      iconColor: "blue"
    },
    {
      label: "付费用户",
      value: stats.value.used,
      description: "占比 40%",
      icon: "CircleCheck",
      iconColor: "green"
    },
    {
      label: "试用中",
      value: stats.value.pending,
      description: "暂转付费",
      icon: "Timer",
      iconColor: "yellow"
    },
    {
      label: "试用已过期",
      value: stats.value.expired,
      description: "暂转付费",
      icon: "WarningFilled",
      iconColor: "orange"
    },
    {
      label: "今日生成内容",
      value: stats.value.todayGenerated || 0,
      description: "包含试用用户",
      icon: "Document",
      iconColor: "green"
    },
    {
      label: "今日发布内容",
      value: stats.value.exchangeRate,
      description: "发布率 70%",
      icon: "DataAnalysis",
      iconColor: "purple"
    }
  ])

  // 页面头部按钮配置（用户看板无导出功能）
  const headerButtons = ref([])

  // 检查是否达到发布上限
  function isPublishLimitReached(user: UserInfo) {
    return user.todayData.published >= user.dailyLimit
  }

  // 获取发布数据信息
  function getPublishInfo(user: UserInfo) {
    const published = user.todayData.published

    // 试用用户显示限制
    if (user.userType === 1 && user.dailyLimit) {
      return {
        published,
        showLimit: true,
        limit: user.dailyLimit
      }
    }

    // 付费用户不显示限制
    return {
      published,
      showLimit: false,
      limit: null
    }
  }

  // 用户类型状态码映射 - 根据状态码匹配显示数据
  const USER_TYPE_CONFIG = {
    0: { text: "付费用户", type: "paid-user" as const, icon: "Coin" }, // 付费用户: #8b21f1
    1: { text: "试用中", type: "trial-active" as const, icon: "Clock" }, // 试用中: #2d5cf2
    2: { text: "试用已过期", type: "trial-expired" as const, icon: "WarningFilled" } // 试用已过期: #c33142
  } as const

  // 版本状态码映射 - 根据状态码匹配显示数据
  const VERSION_CONFIG = {
    0: null, // 无版本显示
    1: { text: "标准版", type: "version-standard" as const }, // 标准版: 灰色
    2: { text: "Pro版", type: "version-pro" as const }, // Pro版: 黑色
    3: { text: "Pro Max", type: "version-pro-max" as const } // Pro Max: 红色
  } as const

  // 根据状态码获取用户类型显示信息
  function getUserTypeDisplay(userType: number) {
    return USER_TYPE_CONFIG[userType as keyof typeof USER_TYPE_CONFIG] || {
      text: "未知",
      type: "info" as const,
      icon: "QuestionFilled"
    }
  }

  // 根据版本码获取版本显示信息
  function getVersionDisplay(version: number) {
    return VERSION_CONFIG[version as keyof typeof VERSION_CONFIG]
  }

  // 根据剩余天数返回试用期显示文本
  function getTrialDisplayText(user: UserInfo) {
    // 只处理试用中用户
    if (user.userType !== 1) {
      return "试用中"
    }

    // 如果没有剩余天数信息，显示默认文本
    if (user.trialDaysRemaining === undefined) {
      return "试用中"
    }

    const daysRemaining = user.trialDaysRemaining

    // 根据剩余天数显示不同文本
    if (daysRemaining <= 0) {
      return "试用中 (已到期)"
    } else if (daysRemaining === 1) {
      return "试用中 (1天剩余)"
    } else if (daysRemaining <= 3) {
      return `试用中 (${daysRemaining}天剩余)`
    } else {
      return "试用中"
    }
  }

  // 获取用户标签类型和图标信息
  function getUserTagInfo(user: UserInfo) {
    const typeInfo = getUserTypeDisplay(user.userType)

    // 如果是试用中，显示剩余天数
    if (user.userType === 1) {
      return {
        ...typeInfo,
        text: getTrialDisplayText(user)
      }
    }

    return typeInfo
  }

  // 无导出逻辑

  // 分页处理
  function handlePageChange(page: number) {
    currentPage.value = page
  }

  function handleSizeChange(size: number) {
    pageSize.value = size
    currentPage.value = 1
  }

  return {
    // 状态
    loading,
    searchKeyword,
    typeFilter,
    statusFilter,
    activityFilter,
    versionFilter,

    // 计算属性
    filteredUsers,
    paginatedUsers,
    userTypeOptions,
    statusOptions,
    activityOptions,
    versionOptions,
    stats,
    statsCards,
    headerButtons,

    // 分页状态
    currentPage,
    pageSize,
    total,

    // 方法
    getUserTypeDisplay,
    getVersionDisplay,
    getTrialDisplayText,
    getUserTagInfo,
    isPublishLimitReached,
    getPublishInfo,
    handlePageChange,
    handleSizeChange
  }
}
